import React, { Component } from "react"
import AddStudent from "./components/AddStudent"
import StudentList from "./components/StudentList"
import StudentTitle from "./components/StudentTitle"



class App extends Component {


  // 定义状态用于管理学员信息
  state = {
    studentList : [
      {
        'number': '1',
        'name': 'as',
        'sex': '男',
        'age': '5',
        'college': '前端',
        'hobbies': [
          '篮球','足球','网球',
        ]
      },
      {
        'number': '2',
        'name': 'bs',
        'sex': '女',
        'age': '35',
        'college': 'Java',
        'hobbies': [
          '篮球','足球'
        ]
      }
    ]
  }

  //  定义方法用于处理studentList的状态  setState是一个异步操作
  addList = (student,callback) => {
  this.setState({
    studentList: [...this.state.studentList, student]
  }, () => {
    callback()
    console.log(this.state.studentList)})
  }

  // 定义删除状态
  deleteList = (number) => {
    // console.log('删除', number)
    // 利用number找到studentList中需要被删除的项 将他删除
    // 处理后的数据重新setState 到 state 之后渲染到页面

    // 1.将原数据进行深拷贝
    const listsData = JSON.parse(JSON.stringify(this.state.studentList))
    // 2. 从拷贝的数据中需要找出删除的哪一项 再删除
    const idx = listsData.findIndex(list => list.number === number)
    // 3. 再删除
    listsData.splice(idx, 1)
    // 4. 将删除后的数据赋值给原数据进行渲染 数据更新
    this.setState({
      studentList: listsData
    },() => {console.log(this.state.studentList)})
  } 


  render () {
    return (
      <div className="container">
        <StudentTitle />
        <AddStudent addList={this.addList} />
        <StudentList studentList = {this.state.studentList}
        deleteList = {this.deleteList}  />
      </div>
    )
  }
}

export default App
